package sysmiddleware

import (
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/app/admin/sys"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/response"
	"os"
	"path/filepath"
)

type DeleteApplicationMiddleware struct {
	svcCtx *svc.ServiceContext
}

func NewDeleteApplicationMiddleware(svcCtx *svc.ServiceContext) *DeleteApplicationMiddleware {
	return &DeleteApplicationMiddleware{
		svcCtx: svcCtx,
	}
}

// 创建数据表字段中间件
func (p DeleteApplicationMiddleware) Handle() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			data        sys.AppReq
			application sys.Application
			menuId      []int
		)
		if err := utils.BindAndValid(c, &data); err != nil {
			response.Fail(c, err.Error())
			c.Abort()
			return
		}
		if err := p.svcCtx.Db.Where("app_id", data.AppId).Find(&application).Error; err != nil {
			panic(err)
		}

		currentDir, _ := os.Getwd()
		parentDir := filepath.Dir(currentDir)
		uiDir := filepath.Dir(parentDir)

		dir := uiDir + "/app/" + application.AppDir
		if res, _ := utils.PathExists(dir); res {
			os.RemoveAll(dir)
		}

		p.svcCtx.Db.Model(&sys.Menu{}).Where("app_id", data.AppId).Pluck("menu_id", &menuId)
		p.svcCtx.Db.Model(&sys.Menu{}).Where("app_id", data.AppId).Delete(true)
		p.svcCtx.Db.Model(&sys.Field{}).Where("menu_id in ?", menuId).Delete(true)
		p.svcCtx.Db.Model(&sys.Action{}).Where("menu_id in ?", menuId).Delete(true)

		c.Set("data", data)
		c.Next()
	}
}
